/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.zhike.framework.common.util;

import com.huize.ladon.apm.common.constant.CommonConstants;
import com.huize.ladon.apm.common.util.HzJsonUtils;
import com.huize.ladon.apm.common.util.IpUtils;
import com.huize.zhike.framework.common.exception.BizException;
import com.huize.zhike.framework.common.param.SystemHostDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 描述: 读取系统Host文件
 *
 * @author tianyuliang
 * @version $Id: SystemHostUtils.java, v0.1 2021/1/21
 */
@Slf4j
public class SystemHostUtils {

    /**
     * 读取host列表
     */
    public static List<String> readHosts() {
        try {
            String fileName = buildHostFile();
            List<String> data = FileUtils.readLines(new File(fileName), CommonConstants.UTF8);
            List<String> lines = BaseUtils.defaultList(data).stream().filter(item -> BaseUtils.isNotEmpty(item) && !item.trim().startsWith("#")).collect(Collectors.toList());
            for (String line : lines) {
                log.debug("读取host数据\t {}", line);
            }
            return lines;
        } catch (IOException e) {
            log.error("读取系统hosts文件异常", e);
            throw new BizException("读取系统hosts文件异常.", e);
        }
    }

    /**
     * 基于应用名前缀，匹配host，包含IP和hostName
     *
     * @param pipelineName
     * @return
     */
    public static Optional<SystemHostDTO> matchApplicationHost(List<String> hosts, String pipelineName) {
        for (String host : hosts) {
            String[] values = host.split("\\s+");
            List<String> items = Stream.of(values).filter(item -> BaseUtils.isNotEmpty(item)).collect(Collectors.toList());
            Optional<String> strHost = items.stream().filter(item -> StringUtils.containsIgnoreCase(item.trim(), pipelineName)).findFirst();
            if (!strHost.isPresent()) {
                continue;
            }

            Optional<String> strIp = items.stream().filter(item -> IpUtils.checkIp(item)).findFirst();
            if (strIp.isPresent()) {
                String ip = strIp.get().trim();
                String hostName = strHost.get().trim();
                return Optional.of(new SystemHostDTO(ip, hostName));
            }
        }
        return Optional.empty();
    }

    private static String buildHostFile() {
        String fileName = null;
        if (BaseUtils.isLinuxSystem()) {
            fileName = "/etc/hosts";
        } else {
            fileName = System.getenv("windir") + "\\system32\\drivers\\etc\\hosts";
        }
        return fileName;
    }

    public static void main(String[] args) {
        List<String> hosts = readHosts();
        Optional<SystemHostDTO> hostMap = matchApplicationHost(hosts, "www.baidu.com");
        System.out.println("匹配结果 = " + (hostMap.isPresent() ? HzJsonUtils.beanToJson(hostMap.get()) : "未查询到"));
    }

}